#!/usr/bin/python3

import urllib
import getopt
import sys
import os
import re
import json
import zjl_util


voice_url_pre = 'http://zjl.hmxingkong.com/speech/speechUrlOld?url=https://zjl.hmxingkong.com/n/novel/content/'
# voice_url_pre = 'http://127.0.0.1:8012/speech/speechUrlOld?url=https://zjl.hmxingkong.com/n/novel/content/'


def get_item_info(id_value):
    get_content_url = 'https://zjl.hmxingkong.com/n/novel/getItemContent'
    form_data = {
        'itemId': id_value,
    }
    form_data = urllib.parse.urlencode(form_data).encode()
    doc = urllib.request.urlopen(get_content_url, form_data).read().decode("utf-8", "ignore")
    j = json.loads(doc)
    # print(j)
    title = j['data']['novelItem']['title'].replace('?', '').replace(':', '_').replace('/', '_')
    this_id = str(j['data']['novelItem']['id'])
    next_id = None
    if 'nextId' in j['data']['novelItem']:
        next_id = str(j['data']['novelItem']['nextId'])
    result = {'title': title, 'this_id': this_id, 'next_id': next_id}
    return result


def down_voice(id_value, dir_path, max_num=999999999999):
    """
    下载小说语音文件
    :param id_value:   地址重要参数https://file.tapd.cn//tfl/captures/2019-12/tapd_39385156_base64_1576564187_71.png
    :param dir_path    文件保存目录
    :param max_num      最多下载个数
    :return:
    """
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)
    i = 0
    redo_count = 0  # 用于记录下载出现错误是记录重试次数，顺利下载完后，次数归0
    while i < max_num and not id_value == None:
        item_info = get_item_info(id_value)
        print(item_info)
        voice_url = voice_url_pre + id_value
        file_path = dir_path + "/" + id_value + "_" + item_info['title'] + ".mp3"
        try:
            zjl_util.download(voice_url, file_path)
        except Exception as e:
            print("request error url:" + voice_url)
            print(e)
            # 提前结束本次循环，再次下载这一章
            if redo_count < 5:
                print('-------\t重试下载  ' + voice_url + '  \t-------')
                redo_count += 1
                continue
            else:
                print('[error] 多次重试后失败')
                exit()

        id_value = item_info['next_id']
        i += 1
        redo_count = 0
        # print('-------------finish save ' + file_path + ' --------------------------')


def main():
    opts, args = getopt.getopt(sys.argv[1:], "shl:", ["url=", "dir="])
    start_url = 'https://zjl.hmxingkong.com/np/content.html?id=342572'
    dir_path = "D:/test/novel_voice/中国队长"
    limit = 9999
    s = 0
    for o, a in opts:
        if o == '-h':
            print("python down_novel_voice.py -s --url=" + start_url + " --dir=D:/test/novel_voice/中国队长 -l 100")
            exit()
        if o == '--url':
            start_url = a
        if o == '--dir':
            dir_path = a
        if o == '-l':
            limit = int(a)
        if o == '-s':
            s = 1
    print('###########starturl##########')
    print(start_url)
    pat_id = 'id=([^&]*)'
    ids = re.compile(pat_id).findall(start_url)
    # print(ids)
    if len(ids) == 0:
        print('[warn]id not found')
        exit()
    id_value = ids[0]
    if s == 1:
        item_info = get_item_info(id_value)
        print(item_info)
    else:
        down_voice(id_value, dir_path, limit)
    print("--------------end------------------")


if __name__ == "__main__":
    main()
